package com.unis.job.sms;

import com.unis.model.system.Meta;
import com.unis.service.system.MetaService;
import com.unis.service.tool.TbXxInfoService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import tk.mybatis.mapper.entity.Example;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Component
public class TestRestfulCommonService {
    @Autowired
    private MetaService metaService;
    @Autowired
    private TbXxInfoService tbXxInfoService;
    public static final String url = "http://10.42.187.161:8089/dap-restful/services/restful/MessageService/sendMessage";


    public String getContent(Map<String, Object> map) throws Exception {
        List<Map<String, String>> list = tbXxInfoService.queryAccountNumEveryDay(map);
        String contentsTogbk = "";
        if (CollectionUtils.isNotEmpty(list)){
            String content = "";
            for (int i = 0; i < list.size() ; i++) {
                if (i < 5){
                    content += list.get(i).get("INFO");
                }
            }
            String sendTime = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
            String contents = "【禁毒资金智能化分析平台】"+sendTime+"时,"+content+" 详情请登录系统查看";
            contentsTogbk = URLEncoder.encode(contents, "UTF-8");
            /*sendMessage(contentsTogbk);*/
        }
        return contentsTogbk;
    }

    public void testQuery(String reqUrl) throws Exception {
        URL restServiceURL;
        try {
            restServiceURL = new URL(reqUrl);
            HttpURLConnection httpConnection = (HttpURLConnection) restServiceURL.openConnection();
            httpConnection.setRequestMethod("GET");
            httpConnection.setRequestProperty("Accept", "application/json");

            if (httpConnection.getResponseCode() != 200) {
                throw new RuntimeException("HTTP GET Request Failed with Error code : "
                        + httpConnection.getResponseCode());
            }

            BufferedReader responseBuffer = new BufferedReader(new InputStreamReader(
                    (httpConnection.getInputStream())));
            String line = "" ;
            StringBuilder sb = new StringBuilder(256);
            while(null != (line = responseBuffer.readLine())) {
                sb.append(line) ;
            }
            /*System.out.println(sb.toString());*/
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Scheduled(cron = "0 0 9 * * ?")
    public void sendMessage()throws Exception{
        List<Map<String, String>> phoneList = tbXxInfoService.queryXijkPhone();
        Set<String> set = new HashSet<>();
        if (CollectionUtils.isNotEmpty(phoneList)){
            for (Map<String, String> mapPhone:phoneList) {
                if (StringUtils.isNotBlank(mapPhone.get("PHONE"))){
                    String[] phoneArray = mapPhone.get("PHONE").split(",");
                    if (phoneArray != null && phoneArray.length > 0){
                        for (String p:phoneArray) {
                            set.add(p);
                        }
                    }
                }
            }
        }
        /*for (String ph:set) {
            String params = "phone="+ph+"&content="+content+"&userAccount=201707191035&userKey=55b3d4a4110e47d4a1f65a10004c1930";
            String reqUrl = url +  "?" + params ;
            testQuery(reqUrl);
        }
*/

        for (String ph:set) {
            Set<String> zhList = new HashSet<>();
            if (CollectionUtils.isNotEmpty(phoneList)){
                for (Map<String, String> mapPhone:phoneList) {
                    if (StringUtils.isNotBlank(mapPhone.get("PHONE"))){
                        String[] phoneArray = mapPhone.get("PHONE").split(",");
                        if (phoneArray != null && phoneArray.length > 0){
                            for (String p:phoneArray) {
                                if (StringUtils.equals(p, ph)){
                                    if (StringUtils.isNotBlank(mapPhone.get("ZH"))){
                                        zhList.add(mapPhone.get("ZH"));
                                    }
                                }
                            }
                        }
                    }
                }
            }
            Map<String, Object> paramMap = new HashMap<>();
            paramMap.put("list", zhList);
            String contentStr = getContent(paramMap);
            if (StringUtils.isNotBlank(contentStr)){
                String params = "phone="+ph+"&content="+contentStr+"&userAccount=201707191035&userKey=55b3d4a4110e47d4a1f65a10004c1930";
                String reqUrl = url +  "?" + params ;
                testQuery(reqUrl);
            }
        }
    }

}
